﻿
Operate();

//提交事件
function SubmitProduct() {
    $('#addproduct_form').form('submit', {
        url: '/EasyUI/DataGrid/AddProduct',
        onSubmit: function () {
            if ($(this).form('enableValidation').form('validate')) {
                if ($("#SelectTypes option:selected").val() === "0" || $("#SelectTypes option:selected").val() === "" || typeof ($("#SelectTypes option:selected").val()) === "undefined") {
                    $.messager.alert('错误提示', '请选择类型', 'error');
                    return false;
                }
                else
                    return true;
            }
            return false;
        },
        success: function (result) {
            if (typeof (result) !== "object")
                result = JSON.parse(result);
            if (result.code === 200) {
                $("#datagrids").datagrid('reload');
                OperateMsg("增加提示", result.msg);
                $('#addproductdiglog').dialog('close');
            }
            else if (result.code === 401)
                $.messager.alert('增加提示', result.msg, 'error');
            else
                $.messager.alert('异常提醒', '系统异常', 'error');
        }, error: function (result) {
            $.messager.alert('异常错误', '异常错误', 'error');
        }
    });
}

//类型json
var clothtypejson = [{ "value": "1", "text": "西装" }, { "value": "2", "text": "衬衫" }, { "value": "3", "text": "裤子" }];

//类型格式化
function formattypes(val, row) {
    if (val === 1)
        return "西装";
    else if (val === 2)
        return "衬衫";
    else if (val === 3)
        return "裤子";
}

//状态选项格式化
function formatstatus(val, row) {
    if (val === 1)
        return "上架";
    else
        return "下架";
}

//操作中心
function Operate() {

    $("#searchs").click(function () {
        var queryParams = $('#datagrids').datagrid('options').queryParams;
        queryParams.Types = $('#clothtype').combobox('getValue');
        var start = $('#startdate').datebox('getValue');
        var end = $('#enddate').datebox('getValue');
        queryParams.Startdate = start;
        queryParams.Enddate = end;
        $('#datagrids').datagrid('options').queryParams = queryParams;
        $("#datagrids").datagrid('reload');
    });

    $("#data-remove").click(function () {
        GetSelected();
    });

    $("#data-export").click(function () {
        var data = {
            "__RequestVerificationToken": $('[name=__RequestVerificationToken]').val(),
            Types: $('#clothtype').combobox('getValue'),
            Startdate: $('#startdate').datebox('getValue'),
            Enddate: $('#enddate').datebox('getValue')
        };
        download("FileExport", data, "post");
    });

    $("#data-import").click(function () {
        $("#fileimport").click();               //模拟点击

        $("#fileimport").change(function () {
            $('#filesubmit').submit();          //模拟提交
        });

        $('#filesubmit').submit(function (event) {
            event.preventDefault(); 
            var formData = new FormData(this);
            $.ajax({
                type: 'post',
                url: '/EasyUI/DataGrid/FileImport',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false
            }).success(function (result) {
                if (typeof (result) !== "object")
                    result = JSON.parse(result);
                if (result.code === 200) {
                    OperateMsg("导入提示", result.msg);
                    location.reload();
                }
                else if (result.code === 401 || result.code === 402 || result.code === 403 || result.code === 404)
                    $.messager.alert('导入提示', result.msg, 'error');
                else
                    $.messager.alert('异常提醒', '系统异常', 'error');
            }).fail(function (jqXHR, textStatus, errorThrown) {
                $.messager.alert('异常错误', '异常错误', 'error');
            });
        });
    });
}

//下载文件
function download(url, data, method) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        jQuery.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        jQuery('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
    };
}

//获取选择项
function GetSelected() {
    var checkedItems = $('#datagrids').datagrid('getChecked');
    var names = [];
    $.each(checkedItems, function (index, item) {
        names.push(item.ProductId);
    });
    var data = { "__RequestVerificationToken": $('[name=__RequestVerificationToken]').val() };
    data["ids"] = names.join(",");
    if (data["ids"] === "") {
        $.messager.alert('删除提示', '请选择删除项', 'error');
        return;
    }

    $.ajax({
        type: "POST",
        url: "/EasyUI/DataGrid/DeleteList",
        data: data,
        success: function (result) {
            if (result.code === 200) {
                $("#datagrids").datagrid('reload');
                OperateMsg("删除提示", result.msg);
            } else if (result.code === 401)
                $.messager.alert('删除提示', result.msg, 'error');
            else
                $.messager.alert('异常提醒', '系统异常', 'error');
        },
        error: function (result) {
            $.messager.alert('异常错误', '异常错误', 'error');
        }
    });
}

//行编辑扩展
$.extend($.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] !== param.field) {
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

//判断{}是否为空
function isEmptyObject(e) {
    for (var name in e) {
        return false;
    }
    return true;
}

var editIndex = undefined;

//编辑结束
function endEditing() {
    if (editIndex == undefined) { return true }
    if ($('#datagrids').datagrid('validateRow', editIndex)) {// 检测  数据是否发生 改变
        $('#datagrids').datagrid('endEdit', editIndex);// 触发 onAfterEdit  方法
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

//编辑完成，保存操作
function onAfterEdit(rowIndex, rowData, changes) {
    if (endEditing()) {
        var data = { "__RequestVerificationToken": $('[name=__RequestVerificationToken]').val() };
        for (change in changes) {
            if (changes[change] === "上架")
                data[change] = 1;
            else if (changes[change] === "下架")
                data[change] = 0;
            else
                data[change] = changes[change];
            data["ProductId"] = rowData.ProductId;
        }
        if (!isEmptyObject(data))
            $.ajax({
                type: "POST",
                url: "/EasyUI/DataGrid/UpdateProduct",
                data: data,
                success: function (result) {
                    if (result.code === 200) {
                        $("#datagrids").datagrid('reload');
                        OperateMsg("修改提示", result.msg);
                    } else if (result.code === 401)
                        $.messager.alert('修改提示', result.msg, 'error');
                    else
                        $.messager.alert('异常提醒', '系统异常', 'error');
                },
                error: function (result) {
                    $.messager.alert('异常错误', '异常错误', 'error');
                }
            });
    }
}

//单击编辑
function onClickCell(index, field, data) {
    if (endEditing()) {
        $('#datagrids').datagrid('selectRow', index).datagrid('editCell', { index: index, field: field, data: data });
        editIndex = index;
    }
}

//双击编辑单元格
function onDblClickCell(index, field, data) {
    if (endEditing()) {
        $('#datagrids').datagrid('selectRow', index).datagrid('editCell', { index: index, field: field, data: data });
        editIndex = index;
    }
}

//双击编辑整行
function onDblClickRow(index, data) {
    if (endEditing()) {
        if (editIndex == undefined) {
            $('#datagrids').datagrid('beginEdit', index);
            editIndex = index;
        }
    }
}

//撤销编辑
function RejectEdit() {
    $('#datagrids').datagrid('rejectChanges');
    editIndex = undefined;
}

//保存编辑修改项
function SaveEdit() {
    $('#datagrids').datagrid("endEdit", editIndex);
}

//日期选择区间
function DateBoxCompare() {
    $('#enddate').datebox().datebox('calendar').calendar({
        validator: function (date) {
            var temp = $('#startdate').datebox("getValue");
            if (temp !== "") {
                var d1 = new Date(Date.parse(temp.replace(/-/g, "/")));
                d1.setDate(d1.getDate() + 1);
                return d1 <= date;
            }
        }
    });
}

//点击开始时间事件
$('#startdate').datebox({
    onSelect: function (date) {
        $('#enddate').datebox('enable');     //启用结束日期控件
        $('#enddate').datebox('reset');      //重置结束日期的值
        DateBoxCompare();
    }
});